<?php

namespace Database\Seeders;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;

class DownloadImage
{
    protected static int $num = 0;

    public static function putImage(): ?string
    {
        // 此网站最多 150 张图片
        if (static::$num > 150) {
            static::$num = 0;
        }

        $url = sprintf('https://api.madouapi.com/images/%u.png', ++static::$num);

        $path = pathinfo($url, PATHINFO_BASENAME);

        if (Storage::exists($path)) {
            return $path;
        }

        $contents = Http::get($url)->body();

        if (Storage::put($path, $contents)) {
            return $path;
        }

        return null;
    }
}
